package com.atguigu.eduService.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.eduService.entity.EduSubject;

import com.atguigu.eduService.entity.excel.SubjectData;
import com.atguigu.eduService.listener.SubjectExcelListener;
import com.atguigu.eduService.mapper.EduSubjectMapper;
import com.atguigu.eduService.service.EduSubjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author Chen Wen bo
 * @since 2021-07-22
 */
@Service
@Transactional
public class EduSubjectServiceImpl extends ServiceImpl<EduSubjectMapper, EduSubject> implements EduSubjectService {

    @Resource
    private EduSubjectMapper eduSubjectMapper;

    //添加课程分类
    @Override
    public void addSubject(MultipartFile file, EduSubjectService eduSubjectService) {

        try {
            EasyExcel.read(file.getInputStream(), SubjectData.class, new SubjectExcelListener(eduSubjectService)).sheet().doRead();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //课程列表
    @Override
    public List<EduSubject> getSubject() {
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id","0");
        List<EduSubject> eduSubjects = eduSubjectMapper.selectList(queryWrapper);
        eduSubjects.forEach(this::getSubjectChildren);
        return eduSubjects;
    }

    private void getSubjectChildren(EduSubject eduSubject){
        QueryWrapper<EduSubject> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id",eduSubject.getId());
        List<EduSubject> eduSubjects = eduSubjectMapper.selectList(queryWrapper);
        eduSubject.setChildren(eduSubjects);
        if (eduSubject.getChildren() != null && eduSubject.getChildren().size() > 0) {
            eduSubject.getChildren().forEach(this::getSubjectChildren);
        }
    }


}
